define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'tasks/index' + location.search,
                    add_url: 'tasks/add',
                    edit_url: 'tasks/edit',
                    del_url: 'tasks/del',
                    multi_url: 'tasks/multi',
                    import_url: 'tasks/import',
                    table: 'tasks',
                }
            });

            var table = $("#table");

            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='user_id']", form).addClass("selectpage").data("source", "user/user/index").data("primaryKey", "id").data("field", "nickname").data("orderBy", "id desc");
                $("input[name='pick_uid']", form).addClass("selectpage").data("source", "user/user/index").data("primaryKey", "id").data("field", "nickname").data("orderBy", "id desc");
                $("input[name='insurance_company_id']", form).addClass("selectpage").data("source", "insurance_company/index").data("primaryKey", "id").data("field", "name").data("orderBy", "id desc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                exportTypes: ['json', 'xml', 'csv', 'txt', 'doc', 'excel'],//设置导出格式
                exportOptions: {
                    fileName: '任务列表' + Moment().format("YYYY-MM-DD"),  //导出表格名称
                    ignoreColumn: [0, 'operate'], //不导出字段
                    ignoreRow: [],
                    csvSeparator: "----",//文本分割
                },

                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'),operate: false},
                        {field: 'order_sn', title: __('Order_sn'),operate: false},
                        {field: 'user_nickname', title: __('User'),operate: false},
                        {field: 'user_id', title: __('User_id'),formatter: Table.api.formatter.search,visible:false},
                        {field: 'date', title: __('Date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'task_items', title: __('Task_items'), operate: false, searchList: Config.searchList, formatter: Table.api.formatter.label},
                        {field: 'car_number', title: __('Car_number'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'province_name', title: __('Province_name'), operate: false},
                        {field: 'city_name', title: __('City_name'), operate: false},
                        {field: 'area_name', title: __('Area_name'), operate: false},
                        {field: 'address', title: __('Address'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'name_4s', title: __('Name_4s'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'insurance_company.name', title: __('Insurance_company'), operate: false},
                        {field: 'insurance_company_id', title: __('Insurance_company_id'),formatter: Table.api.formatter.search,visible:false},
                        {field: 'receptionist', title: __('Receptionist'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'pick_nickname', title: __('Pick_uid'),operate: false},
                        {field: 'pick_uid', title: __('Pick_uid'),formatter: Table.api.formatter.search,visible:false},
                        {field: 'sure_name', title: __('Sure_name'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'service_item', title: __('Service_item'),operate: false, searchList: Config.searchList, formatter: Table.api.formatter.label},
                        {field: 'price', title: __('Price'), operate:'BETWEEN'},
                        {field: 'status', title: __('Status'), searchList: {"-3":__('Status -3'),"-2":__('Status -2'),"-1":__('Status -1'),"0":__('Status 0'),"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3'),"4":__('Status 4'),"5":__('Status 5'),"6":__('Status 6'),"7":__('Status 7')}, formatter: Table.api.formatter.status},
                        // {field: 'settle_status', title: __('Settle_status'), searchList: {"-1":__('Settle_status -1'),"0":__('Settle_status 0'),"1":__('Settle_status 1')}, formatter: Table.api.formatter.status},
                        {field: 'return', title: __('Return_id'),
                            formatter:function (value,row,index) {
                                return value ? value.name : '';
                            },
                        },
                        {field: 'settle', title: __('Settle_price'),
                            formatter:function (value,row,index) {
                                return value ? value.price : '';
                            },
                        },
                        {field: 'remark', title: __('Remark'), operate: false, table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'models', title: __('Models'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'images', title: __('Images'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.images},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:false, addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'detail',
                                    title: __('详情'),
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-eye',
                                    url: 'tasks/detail',
                                    callback: function (data) {
                                        // console.log('回传结果'+ data)
                                    }
                                },
                                {
                                    name: 'settle',
                                    title: __('结算'),
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-check-square-o',
                                    url: 'tasks/settle',
                                    callback: function (data) {
                                        // console.log('回传结果'+ data)
                                    }
                                },
                            ],
                            formatter: function (value, row, index) {
                                var that = $.extend({}, this);
                                var table = $(that.table).clone(true);
                                if (row.settle_status != 0){
                                    $(table).data("operate-settle", null);    //移除 结算 按钮
                                }
                                $(table).data("operate-edit", null);    //移除 编辑按钮
                                that.table = table;
                                return Table.api.formatter.operate.call(that, value, row, index);
                            }
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            //指定搜索条件
            $(document).on("click", ".btn-export", function () {
                var ids = Table.api.selectedids(table);
                var page = table.bootstrapTable('getData');
                var all = table.bootstrapTable('getOptions').totalRows;

                Layer.confirm("请选择导出的选项!<form action='" + Fast.api.fixurl("tasks/export") + "' method='post' target='_blank'><input type='hidden' name='ids' value='' /><input type='hidden' name='filter' ><input type='hidden' name='op'><input type='hidden' name='search'><input type='hidden' name='columns'></form>", {
                    title: '导出数据',
                    btn: ["选中项(" + ids.length + "条)", "本页(" + page.length + "条)", "全部(" + all + "条)"],
                    success: function (layero, index) {
                        $(".layui-layer-btn a", layero).addClass("layui-layer-btn0");
                    }, yes: function (index, layero) {
                        if (ids.length == 0){
                            layer.msg('导出数据为空');
                            return false;
                        }
                        submitForm(ids.join(","), layero);
                        return false;
                    },
                    btn2: function (index, layero) {
                        var pageIds = page.map(item => item.id);
                        submitForm(pageIds, layero);
                        layer.close(index);
                        return false;
                    },
                    btn3: function (index, layero) {
                        submitForm("all", layero);
                        layer.close(index);
                        return false;
                    }
                })
            });
            var submitForm = function (ids, layero) {
                var options = table.bootstrapTable('getOptions');
                console.log(options);
                var columns = [];
                $.each(options.columns[0], function (i, j) {
                    if (j.field && !j.checkbox && j.visible && j.field != 'operate') {
                        columns.push(j.field);
                    }
                });
                var search = options.queryParams({});
                $("input[name=search]", layero).val(options.searchText);
                $("input[name=ids]", layero).val(ids);
                $("input[name=filter]", layero).val(search.filter);
                $("input[name=op]", layero).val(search.op);
                $("input[name=columns]", layero).val(columns.join(','));
                $("form", layero).submit();
            };
        },
        range: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'tasks/range' + location.search,
                    add_url: 'tasks/add',
                    edit_url: 'tasks/edit',
                    del_url: 'tasks/del',
                    multi_url: 'tasks/multi',
                    import_url: 'tasks/import',
                    table: 'tasks',
                }
            });

            var table = $("#table");

            //在普通搜索渲染后
            table.on('post-common-search.bs.table', function (event, table) {
                var form = $("form", table.$commonsearch);
                $("input[name='take_range']", form).addClass("selectpage").data("source", "tasks/get_range").data("primaryKey", "value").data("field", "label").data("orderBy", "id asc");
                $("input[name='pick_range']", form).addClass("selectpage").data("source", "tasks/get_range").data("primaryKey", "value").data("field", "label").data("orderBy", "id asc");
                $("input[name='service_range']", form).addClass("selectpage").data("source", "tasks/get_range").data("primaryKey", "value").data("field", "label").data("orderBy", "id asc");
                $("input[name='return_range']", form).addClass("selectpage").data("source", "tasks/get_range").data("primaryKey", "value").data("field", "label").data("orderBy", "id asc");
                Form.events.cxselect(form);
                Form.events.selectpage(form);
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible: true,
                columns: [
                    [
                        {field: 'id', title: __('Id'),operate: false},
                        {field: 'order_sn', title: __('Order_sn'),operate: false},
                        {field: 'user.nickname', title: __('User'),operate: false},
                        {field: 'date', title: __('Date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'models', title: __('Models'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'car_number', title: __('Car_number'), operate: 'LIKE', table: table, class: 'autocontent', formatter: Table.api.formatter.content},
                        {field: 'status', title: __('Status'), searchList: {"-3":__('Status -3'),"-2":__('Status -2'),"-1":__('Status -1'),"0":__('Status 0'),"1":__('Status 1'),"2":__('Status 2'),"3":__('Status 3'),"4":__('Status 4'),"5":__('Status 5'),"6":__('Status 6')}, formatter: Table.api.formatter.status},
                        {field: 'take_range', title: __('Take_range'), operate: '<=', autocomplete:false, formatter: Table.api.formatter.formatDayTime},
                        {field: 'pick_range', title: __('Pick_range'), operate: '<=', autocomplete:false, formatter: Table.api.formatter.formatDayTime},
                        {field: 'service_range', title: __('Service_range'), operate: '<=', autocomplete:false, formatter: Table.api.formatter.formatDayTime},
                        {field: 'return_range', title: __('Return_range'), operate: '<=', autocomplete:false, formatter: Table.api.formatter.formatDayTime},
                        {field: 'range', title: __('Range'), operate: false, autocomplete:false, formatter: Table.api.formatter.formatDayTime},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'finishtime', title: __('Finishtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate,
                        //     buttons: [
                        //         {
                        //             name: 'detail',
                        //             title: __('详情'),
                        //             classname: 'btn btn-xs btn-info btn-dialog',
                        //             icon: 'fa fa-eye',
                        //             url: 'tasks/detail',
                        //             callback: function (data) {
                        //                 // console.log('回传结果'+ data)
                        //             }
                        //         },
                        //     ],
                        //     formatter: function (value, row, index) {
                        //         var that = $.extend({}, this);
                        //         var table = $(that.table).clone(true);
                        //         $(table).data("operate-edit", null);    //移除 编辑按钮
                        //         $(table).data("operate-del", null);    //移除 删除按钮
                        //         that.table = table;
                        //         return Table.api.formatter.operate.call(that, value, row, index);
                        //     }
                        // }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'tasks/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '140px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'tasks/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'tasks/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },

        detail: function () {
            $(document).on('click', '.btn-callback', function () {
                var id = $('.row_id').val();
                var flag = $(this).val();
                var notice = '同意取件人拒接，任务将被取消？';
                if (flag == 0){
                    notice = '不同意拒接，任务将重新开始倒计时?';
                }
                layer.confirm(notice,{
                    btn:['确定','取消']//按钮
                },function () {
                    $.post('tasks/refuse', {id:id,flag:flag},function (result) {
                        layer.msg(result.msg,{'time':1000},function () {
                            layer.closeAll();
                            Fast.api.close(result.code);
                        });
                    },'json');
                });
            });

            /*! 注册 data-tips-image 事件行为 */
            $('body').on('click', '[data-tips-image]', function () {
                var img = new Image();
                var imgWidth = this.getAttribute('data-width') || '480px';
                img.onload = function () {
                    var $content = $(img).appendTo('body').css({background: '#fff', width: imgWidth, height: 'auto'});
                    Layer.open({
                        type: 1, area: imgWidth, title: false, closeBtn: 1,
                        skin: 'layui-layer-nobg', shadeClose: true, content: $content,
                        end: function () {
                            $(img).remove();
                        },
                        success: function () {

                        }
                    });
                };
                img.onerror = function (e) {

                };
                img.src = this.getAttribute('data-tips-image') || this.src;
            });

            Table.api.formatter.image =  function(value){
                return "<a href='javascript:void(0)' data-tips-image='"+value+"'><img src='"+value+"' class='img-sm img-center' ></a>";
            };
        },
        add: function () {
            Controller.api.bindevent();
        },
        settle: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
